package com.personal.common.util;

import java.util.HashMap;
import java.util.Map;

public class MySqlEncoder {
	private static Map<String, String> referencesMap = new HashMap<String, String>();

	static {
		referencesMap.put("_", "\\_");
		referencesMap.put("'", "\\'");
		referencesMap.put("%", "\\%");
		referencesMap.put("\"", "\\\"");
		referencesMap.put("//", "\\/\\/");
		referencesMap.put("\\", "\\\\\\\\");
		referencesMap.put(" ", "\\ ");
		referencesMap.put("/0", "\\/0");
		referencesMap.put("/b", "\\/b");
		referencesMap.put("/t", "\\/t");
		referencesMap.put("/f", "\\/f");
	}

	// escape sql tag with the source code.
	public static String encode(String source) {
		if (source == null)
			return "";

		StringBuffer sbuffer = new StringBuffer(source.length());

		for (int i = 0; i < source.length(); i++) {
			String c = source.substring(i, i + 1);

			if (referencesMap.get(c) != null) {
				sbuffer.append(referencesMap.get(c));
			} else {
				sbuffer.append(c);
			}
		}
		return sbuffer.toString();
	}

}
